import type { FC } from 'react';
import { Spin, Button } from 'antd';
import { useRef, useEffect } from 'react';
import { useSafeState, useMemoizedFn } from 'ahooks';
import { initAMap } from './helper';
import type { MapRes, PoiItem } from './types';
import Context from './context';
import styles from './styles.module.less';

export type MapViewProps = {
  children?: (res: MapRes) => any;
  onOk?: (item: PoiItem) => void;
}

const MapView: FC<MapViewProps> = (props) => {
  const mapRes = useRef<MapRes>();
  const el = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useSafeState(true);
  const [selectedPoi, setSelectedPoi] = useSafeState<PoiItem>();

  const initialization = useMemoizedFn(() => {
    initAMap(el.current).then(res => {
      mapRes.current = res;
      setLoading(false);
    });
    return () => {
      mapRes.current?.destroy();
    };
  });

  useEffect(initialization, [initialization]);

  const handleOk = useMemoizedFn(() => {
    if (selectedPoi) props.onOk?.(selectedPoi);
  })

  const renderChildren = (res?: MapRes) => {
    if (loading || !res) return null;
    return props.children?.(res);
  }

  return (
    <Context.Provider
      value={{
        selectedPoi,
        setSelectedPoi
      }}
    >
      <Spin spinning={loading}>
        <div className={styles.map_wrapper}>
          <div className={styles.map_container}>
            <div ref={el} className={styles.map_view} />
            {renderChildren(mapRes.current)}
          </div>
          <div className={styles.buttons}>
            <Button
              type="primary"
              onClick={handleOk}
              disabled={!selectedPoi}
            >
              确认选择
            </Button>
          </div>
        </div>
      </Spin>
    </Context.Provider>
  );
}

export default MapView;